<?php
/*数据同步代码*/
header('Content-type:text/html;charset=utf-8');
include 'ftpClass.php';

echo ('同步中');

$ftp = new ftp('122.14.217.130', 21, 'ftptest', 'ftptest');     // 打开FTP连接
//遍历递归主服务器文件
$localFileArr = array();
//获取本地文件夹所有内容
function getLocalFiles($dir)
{
    global $localFileArr, $localDir;
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $prefixDir = $dir . '/';
        if (is_dir($prefixDir . $file)) {
            getLocalFiles($prefixDir . $file);
        } else {
            $localFileArr[] = preg_replace("/\.\/testdir\//", '', $prefixDir . $file);
        }
    }
}

$localDir = './testdir';
getLocalFiles($localDir);
//print_r($localFileArr);
//遍历递归从服务器文件
$remoteFileArr = array();
//获取远程文件夹所有内容
function getRemoteFiles($dir)
{
    global $ftp, $remoteFileArr, $remoteDir;
    //获取该目录的所有文件
    $list = $ftp->read($dir);
    foreach ($list as $value) {
        if ($value == '.' || $value == '..') {
            continue;
        }
        $currentValue = $dir . '/' . $value;
        //如果是文件夹 则继续遍历
        if ($ftp->isFtpDir($currentValue)) {
            getRemoteFiles($currentValue);

        } else {
            $remoteFileArr[] = trim($value, '/');
        }

    }
}

$remoteDir = '/';
getRemoteFiles($remoteDir);
//print_r($remoteFileArr);
//对比  将不同的筛选出来
$needUploadFileArrs = array_diff($localFileArr, $remoteFileArr);
//var_dump($needUploadFileArrs);

//永不超时
set_time_limit(0);

//进行同步
foreach ($needUploadFileArrs as $needUploadFileArr) {
    $ftp->up_file($localDir . '/' . $needUploadFileArr, $remoteDir . $needUploadFileArr);
}

//关闭连接
$ftp->close();

echo '同步成功';


?>